<?php
namespace catchAdmin\registration\controller;

use catchAdmin\registration\excel\FollowExport;
use catcher\CatchResponse;
use catcher\base\CatchRequest;
use catcher\base\CatchController;
use catchAdmin\registration\request\SaveRequest;
use catchAdmin\registration\request\PushRequest;
use catchAdmin\registration\request\MyRequest;
use catchAdmin\registration\service\TaskService;
use app\common\model\Follow as FollowModel;
use app\common\model\Followtask as FollowtaskModel;
use app\common\model\PatientInfo as PatientInfoModel;
use catchAdmin\permissions\model\Users as UsersModel;
use app\common\business\Follow as FollowBusiness;
use catchAdmin\registration\service\StatisticsService;
use app\common\model\FollowPushQuestionnaire as PushQuestModel;
use catcher\Code;
use catcher\exceptions\FailedException;
use app\common\model\FollowHistory as HistoryModel;
use catcher\library\excel\Excel;
use catcher\Utils;
use app\common\lib\Redis;
use app\common\model\OverallConfig as OverallModel;
use catchAdmin\registration\excel\FollowTaskExport;
use catchAdmin\registration\excel\MyFollowExport;

class Task extends CatchController
{
    protected $followtask;

    public function __construct(FollowtaskModel $followtask)
    {
        $this->followtask = $followtask;
    }

    /**
     * 列表
     *
     * @time 2022年09月21日
     * @return \think\response\Json
     */
    public function index(): \think\response\Json
    {
       return CatchResponse::paginate($this->followtask->getList());
    }

    /**
     * 创建随访任务
     *
     * @time 2022年09月21日
     * @param SaveRequest $request
     * @return \think\response\Json
     */
    public function save(SaveRequest $request): \think\response\Json
    {
        $req = $request->param();
        $userInfo = request()->user();

        //收案创建随访需将患者数赋给随访员
        if (isset($req['type']) && $req['type'] == 1) {
            $req['follow_staff'][0]['count'] = $req['patient_num'];
        }
   
        //患者收案-群发表单|添加计划 全选患者
        if (isset($req['is_all']) && $req['is_all'] === true) {

            //$req['id'] = (new PatientInfoModel())->getAllPatientIds($req['group_id'], request()->user()->id, 'id');
            if (!isset($req['key'])) {
                throw new FailedException('key不能为空');
            }

            if (!Redis::getInstance()->redis->exists("collect_pids:" . $req['key'])) {
                throw new FailedException('页面缓存已过期，请重新加载页面');
            }
            $collectData = Redis::getInstance()->redis->get("collect_pids:" . $req['key']);
            $req['id'] = json_decode($collectData, true);

            $req['status'] = 1;
            $req['starttime'] = date("Y-m-d");
            Redis::getInstance()->redis->del("collect_pids:" . $req['key']);
        }

        //随访全选患者
        if (isset($req['select_all']) && $req['select_all'] === true) {
            $redisKey = 'follow_select_all:'.$userInfo['doctor_code'];
            $pids = [];
            if (Redis::getInstance()->redis->exists($redisKey)) {
                $redisData = Redis::getInstance()->redis->get($redisKey);
                $pids = json_decode($redisData, true);
            }

            if (empty($pids)) {
                throw new FailedException("暂无数据");
            }
            $req['id'] = $pids;
        }
        return CatchResponse::success((new TaskService())->saveTask($req));
    }  

    /**
     * 条件查询患者
     * 
     * @time 2022年09月26日
     * @return \think\response\Json
     */
    public function get_patient()
    {
        return CatchResponse::success((new PatientInfoModel())->getWherePatient(2));
    }

    /**
     * 条件查询患者统计项筛选
     * 
     * @time 2022年10月12日
     * @return \think\response\Json
     */
    public function get_patient_stati_screen(): \think\response\Json
    {
        $list = (new FollowBusiness())->screenWaitFollowPatient();
        $result = array_merge($list, ["code" => Code::SUCCESS, "message" => "success"]);
        return json($result);
    }

    /**
     * 随访任务患者
     *
     * @time 2022年09月21日
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function my_follow_patient(CatchRequest $request): \think\response\Json
    {
        $req = $request->param();
        if (empty($req['id'])) {
            throw new FailedException("参数不能为空");
        }
        //type 2 分娩随访计划
        if (isset($req['type']) == 2) {
            $list = (new FollowModel())->getLists();
        }else{
            $list = (new FollowModel())->getLists2();
        }
        return CatchResponse::paginate($list);
    }

    /**
     * 随访任务详情统计
     *
     * @time 2022年09月21日
     * @param MyRequest $request
     * @return \think\response\Json
     */
    public function my_follow_statistics(MyRequest $request): \think\response\Json
    {
        return CatchResponse::success((new TaskService())->getTaskAggregation($request->param('id')));
    }

    /**
     * 推送渠道问卷
     *
     * @time 2022年09月21日
     * @param PushRequest $request
     * @return \think\response\Json
     */
    public function push(CatchRequest $request): \think\response\Json
    { 
       return CatchResponse::success((new TaskService())->pushQuestionnaire($request->param()));
    }

    /**
     * 获取随访人员
     *
     * @time 2022年10月13日
     * @return \think\response\Json
     */
    public function get_follow_personnel(): \think\response\Json
    {
        return CatchResponse::success((new UsersModel())->getPersonnel());
    }

    /**
     * 开始随访任务
     * @time 2022年10月13日
     * @return \think\response\Json
     */
    public function start_task(CatchRequest $request): \think\response\Json
    {
        return CatchResponse::success($this->followtask->saveStatus($request->param('id'), ['status' => $request->param('status')]));
    }

    /**
     * 删除随访任务患者
     * @time 2022年10月14日
     * @return \think\response\Json
     */
    public function del_task_personnel(CatchRequest $request): \think\response\Json
    {
        return CatchResponse::success((new FollowModel())->del($request->param('id')));
    }

    /**
     * 患者详情-随访问卷记录
     * @time 2022年10月14日
     * @return \think\response\Json
     */
    public function patient_follow_record(CatchRequest $request): \think\response\Json
    {
        $req = $request->post();

        $history_id = '';
        if (isset($req['history_id']) && !empty($req['history_id'])) {
            $history_id = $req['history_id'];
        }
        return CatchResponse::success((new FollowModel())->getRecord($req['id'], $history_id));
    }

    /**
     * 删除随访计划
     * @time 2023年2月16日
     * @return \think\response\Json
     */
    public function del_task(MyRequest $request): \think\response\Json
    {
        return CatchResponse::success((new TaskService())->delTask($request->param('id')));
    }

    /**
     * 编辑随访计划
     * @time 2023年2月16日
     * @return \think\response\Json
     */
    public function edit_task(MyRequest $request): \think\response\Json
    {
        return CatchResponse::success((new TaskService())->editTask($request->param('id')));
    }

    /**
     * 随访任务详细统计
     * @time 2023年2月21日
     * @return \think\response\Json
     */
    public function task_detailed_statistics(MyRequest $request): \think\response\Json
    {
        return CatchResponse::success((new StatisticsService())->TaskDetailedStatistics($request->param('id')));
    }

    /**
     * 随访任务详细统计图表
     * @time 2023年2月22日
     * @return \think\response\Json
     */
    public function task_detailed_chart(MyRequest $request): \think\response\Json
    {
        return CatchResponse::success((new StatisticsService())->TaskDetailedChartStatistics($request->param('id')));
    }

    /**
     * 科室随访统计
     *
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function department_follow_statistics(CatchRequest $request): \think\response\Json
    {
        return CatchResponse::success((new TaskService())->getFollowDepartmentReport($request->param()));
    }

    /**
     * 科室随访统计详情
     *
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function department_follow_statistics_detailed(CatchRequest $request): \think\response\Json
    {
        return CatchResponse::success((new FollowModel())->getFollowDepartmentDetailedList($request->param()));
    }

    /**
     * 个人随访统计
     *
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function personal_follow_statistics(CatchRequest $request): \think\response\Json
    {
        return CatchResponse::success((new FollowModel())->getFollowIndividualList($request->param()));
    }

    /**
     * 个人随访统计详情
     *
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function personal_follow_statistics_detailed(CatchRequest $request): \think\response\Json
    {
        return CatchResponse::success((new FollowModel())->getFollowIndividualDetailedList($request->param()));
    }
    
    /**
     * 获取随访任务
     *
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function get_tasks(CatchRequest $request): \think\response\Json
    {
        return CatchResponse::success($this->followtask->getConditionData([],'id,taskname'));
    }

    /**
     * 随访表单统计
     *
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function form_follow_statistics(CatchRequest $request): \think\response\Json
    {
        return CatchResponse::success((new PushQuestModel())->getFollowFormList($request->param()));
    }

    /**
     * 获取最新一次随访记录
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function getLatestFollowRecord(CatchRequest $request): \think\response\Json
    {
        $req = $request->param();
        if (!isset($req['patientId']) || empty($req['patientId'])) {
            throw new FailedException("患者id不能为空");
        }
        $ret = (new HistoryModel)->where('patientId', $req['patientId'])->order('_id', 'desc')->find();
        if ($ret) {
            $mode = config('dictionary.follow_mode');
            $ret['mode'] = $mode[$ret['mode']];
        }
        return CatchResponse::success($ret??[]);
    }

    /**
     * 获取全局配置随访周期
     * @return \think\response\Json
     */
    public function getFollowCycle(): \think\response\Json
    {
        $overall = (new OverallModel())->getConditionOne(['flag' => 'sfzq'], 'status, parameter');

        $cycle = 0;
        if ($overall['status'] === true){
            $cycle = (int)$overall['parameter'];
        }
        return CatchResponse::success(['cycle' => $cycle]);
    }

    /**
     * 卫健委上报导出
     * @return \think\response\Json
     */
    public function exports(Excel $excel, FollowTaskExport $followExport)
    {
        set_time_limit(0);
        ini_set("memory_limit","2G");

        return CatchResponse::success($excel->save($followExport, Utils::publicPath('export/follows')));
    }

    /**
     * 随访任务导出
     * @return \think\response\Json
     */
    public function taskExports(Excel $excel, FollowExport $followExport)
    {
        set_time_limit(0);
        ini_set("memory_limit","2G");
        return CatchResponse::success($excel->save($followExport, Utils::publicPath('export/follows')));
    }

    /**
     * 随访任务详情导出
     * @return \think\response\Json
     */
    public function myFollowExports(Excel $excel, MyFollowExport $followExport)
    {
        set_time_limit(0);
        ini_set("memory_limit","2G");
        return CatchResponse::success($excel->save($followExport, Utils::publicPath('export/follows')));
    }

    /**
     * 预随访患者统计
     * @return \think\response\Json
     */
    public function preFollowPatientList(CatchRequest $request): \think\response\Json
    {
        $req = $request->param();
        return CatchResponse::success((new FollowBusiness())->preFollowPatientStatistics($req));
    }

    /**
     * 历年随访率统计
     * @return \think\response\Json
     */
    public function test(CatchRequest $request): \think\response\Json
    {
        return CatchResponse::success();
    }

    /**
     * 批量模糊搜索随访计划
     * @return \think\response\Json
     */
    public function batchFuzzyTaskname(CatchRequest $request): \think\response\Json
    {
        $req = $request->param();

        $where = [];
        if (isset($req['taskname'])) {
            $where[] = ['taskname', 'Like', $req['taskname']];
        }
        $list = $this->followtask->where($where)->field('id,taskname')->select();
        return CatchResponse::success($list);
    }
}